package com.cm.sys.framework.application;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cm.sys.framework.execption.BusinessException;

/**
 * 自定义请求参数处理器
 * 
 * @author yxq18
 *
 */
public class RequestParameter {
    private JSONObject data;
    private HttpServletRequest reqeust;
    private String token;

    public RequestParameter(HttpServletRequest request) {
        this.reqeust = request;

        String token = request.getHeader("X-Session-Token");

        Enumeration<String> es = reqeust.getParameterNames();
        while (es.hasMoreElements()) {
            if (this.data == null) {
                this.data = new JSONObject();
            }
            String name = es.nextElement();

            this.data.put(name, reqeust.getParameter(name));
        }

        if (this.data == null) {
            StringBuilder sb = new StringBuilder();
            try (BufferedReader reader = request.getReader();) {
                char[] buff = new char[1024];
                int len;
                while ((len = reader.read(buff)) != -1) {
                    sb.append(buff, 0, len);
                }
                reader.close();
            } catch (IOException e) {

                throw new BusinessException("IO流异常");

            }
            this.data = JSON.parseObject(sb.toString());
        }

        this.token = token;
    }

    public JSONObject getparameters() {
        return this.data == null ? new JSONObject() : this.data;
    }

    public HttpServletRequest getReqeust() {
        return this.reqeust;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

}
